//
//  RequsetUtil.m
//  GJDigitalSDK
//
//  Created by wbb on 2021/11/10.
//

#import "RequsetUtil.h"
#define Kboundary  @"----WebKitFormBoundaryjh7urS5p3OcvqXAT"
#define KNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]


@interface RequsetUtil ()<NSURLSessionDataDelegate>

@end


@implementation RequsetUtil




-(void)uploadWav
{
    //01 确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://robot.guiji.ai/aibase/call/20131"];

    //02 创建"可变"请求对象
    NSMutableURLRequest *request  =[NSMutableURLRequest requestWithURL:url];

    //03 修改请求方法"POST"
    request.HTTPMethod = @"POST";

    //'设置请求头:告诉服务器这是一个文件上传请求,请准备接受我的数据
    //Content-Type:multipart/form-data; boundary=分隔符
    NSString *headerStr = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary];
    headerStr = @"audio/wave;charset=UTF-8";
    [request setValue:headerStr forHTTPHeaderField:@"Content-Type"];
    //04 拼接参数-(设置请求体)
    //'按照固定的格式来拼接'
    NSData *data = [self getBodyData];
    //!!!! request.HTTPBody = data;

    //05 创建会话对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //06 根据会话对象创建uploadTask请求
    /*
     第一个参数:请求对象
     第二个参数:要传递的是本应该设置为请求体的参数
     第三个参数:completionHandler 当上传完成的时候调用
     data:响应体
     response:响应头信息
     */
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        // 08 解析服务器返回的数据
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
    }];

    //07 发送请求
    [uploadTask resume];
}

-(void)upload{
    //01 确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://robot.guiji.ai/aibase/call/20131"];

    //02 创建"可变"请求对象
    NSMutableURLRequest *request  =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];

    //03 修改请求方法"POST"
    request.HTTPMethod = @"POST";

    //'设置请求头:告诉服务器这是一个文件上传请求,请准备接受我的数据
    //Content-Type:multipart/form-data; boundary=分隔符
    NSString *headerStr = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",Kboundary];
    headerStr = @"audio/wave;charset=UTF-8";
    [request setValue:headerStr forHTTPHeaderField:@"Content-Type"];
    //05 创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //06 根据会话对象创建uploadTask请求
    /*
     第一个参数:请求对象
     第二个参数:要传递的是本应该设置为请求体的参数
     第三个参数:completionHandler 当上传完成的时候调用
     data:响应体
     response:响应头信息
     */

    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:[
                                                                                          self getUrl]
                                                      completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"error ==== %@",error.localizedDescription);
            return;
        }
        NSString * message = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",message);

        if (self.requestDataBlock) {
            self.requestDataBlock(message);
        }
    }];
    
    //07 发送请求
    [uploadTask resume];
}
- (NSURL *)getUrl {
    // 沙盒目录Documents地址
    NSString *recordUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // caf文件路径
    NSURL *tmpUrl = [NSURL URLWithString:[recordUrl stringByAppendingPathComponent:@"selfRecord.wav"]];
    return tmpUrl;
}
-(NSData *)getBodyData
{
    
    NSError *error = nil;
    // 沙盒目录Documents地址
    NSString *recordUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // caf文件路径
    NSURL *tmpUrl = [NSURL URLWithString:[recordUrl stringByAppendingPathComponent:@"selfRecord.wav"]];
    //从路径下检查是否有文件
    NSData *audioData = [NSData dataWithContentsOfFile:[tmpUrl path] options: 0 error:&error];


    //拼接
    return audioData;
}

#pragma mark NSURLSessionDataDelegate
/*
 bytesSent:本次上传的数据大小
 totalBytesSent:已经上传数据的总大小
 totalBytesExpectedToSend:文件的总大小
 */
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    NSLog(@"%f",1.0 * totalBytesSent /totalBytesExpectedToSend);
}

@end

